<template>
  <el-form ref="add" :model="data" :rules="rules" label-width="100px">
    <el-form-item label="分类名称" prop="name">
      <el-input v-model="data.name" />
    </el-form-item>
    <el-form-item label="排序" prop="sort">
      <el-input v-model.number="data.sort" />
    </el-form-item>
    <el-form-item>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="addCate"> 确认 </el-button>
      </span>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { addCateApi } from '@/api/category.js'
import { ref, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  categoryType: {
    required: true
  }
})
const emits = defineEmits(["closeAddDia"])
//添加分类需要数据
const data = ref({
  name: '',
  sort: null
})

const rules = {
  name: [{ required: true, message: '必填项', trigger: 'blur' }],
  sort: [{ required: true, message: '必填项', trigger: 'blur' }],
}
const add = ref()
//添加分类
const addCate = () => {
  add.value.validate(async (isOk) => {
    if (!isOk) return
    try {
      const res = await addCateApi({
        type: props.categoryType,
        ...data.value
      })
      if (res.code === 200) {
        ElMessage.success('添加成功')
        emits("closeAddDia")
      } else {
        ElMessage.error(res.msg)
      }
    } catch (err) {
      console.log(err);
    }
    add.value.resetFields()
  })
}

const close = () => {
  add.value.resetFields()
  emits("closeAddDia")
}
</script>
